<uieip type="page" value="login" debug="true" timeout="5000"></uieip>
<uieip type="reg" value="console,model"></uieip>
<!DOCTYPE html>
<html>

<head>
    <uieip type="file" value="inc" src="/yqwin/easyui/include.txt" cache="true" minute="1440"></uieip>
    <uieip type="file" value="css" src="/yqwin/css/yqwin.min" cache="false"></uieip>
    <uieip type="file" value="js" src="/yqwin/src/yqwin.min" cache="false"></uieip>
    <script src="/yqwin/src/yq.flowview.js"></script>
    <title>MdiWin Demo - edit</title>
</head>

<body>
    <div id="main_edit"></div>
    <a id="btn_EditWindow" href="javascript:main_fun.save();" class="easyui-linkbutton" data-options="">save</a>
    <a id="btn_EditWindow" href="javascript:page_fun.close();" class="easyui-linkbutton" data-options="">close</a>
    <div id="main_wf"></div>
    <script>
        <uieip type="tmpl" value="model.params"></uieip>

        $(function () {
            main_fun.init();
        });

        var page_fun = {
            p_params: {},
            init: function () {
                main_fun.set_row(page_fun.p_params.row);
            },
            close: function () {
                $.yqWinPopEdit("close");
            }
        }

        var main_fun = {
            id: "main_edit",
            init: function () {
                $.yqWinPopEdit("options", {
                    _tb: _tb,
                    callback: function (res) {
                        if (res.error == 0) {
                            page_fun.p_params = res;
                            main_fun.init_after(res.titles, res.model);
                        }
                    }
                });
            },
            init_after: function (titles, model) {
                var opt = {
                    titles: titles,
                    model: model,
                    row: {},
                    loadDefault: false,   //加载默认值
                    controlType: 1,    //默认显示类型 1-textbox模式  2-div模式
                    isEdit: true,
                    blankTag: "*",     //值不能为空，标题附加标记
                    beforBindingTitle: function (titles, callback) {
                        console.log("beforBindingTitle", titles);
                        callback(titles);
                    }, //标题绑定前
                    afterBindingTitle: function () {
                        page_fun.init();
                    },   //标题绑定后
                    endEditing: function (row) {   //ok.....
                        console.log("endEditing", row);
                    },
                    afterSetRow: function (row) {
                        wf_fun.load();
                    }
                };
                $("#" + main_fun.id).yqFormEdit(opt);
            },
            verId: function () {
                return _tb.verId;
            },
            get_row: function () {
                return $("#" + main_fun.id).yqFormEdit("getRow");
            },
            set_row: function (row) {
                $("#" + main_fun.id).yqFormEdit("setRow", row);
            },
            upp_row: function () {
                var row = main_fun.get_row();
                $.yqWinPopEdit("get", {
                    row: row,
                    _tb: _tb,
                    callback: function (tf, row) {
                        if (tf) {
                            main_fun.set_row(row);
                            if (page_fun.p_params.type == "base") {
                                $.yqWinPopEdit("refresh", {
                                    row: row,
                                    action: "upp",
                                });
                            }
                        }
                    }
                });
            },
            save: function () {
                var _opt = $("#" + main_fun.id).yqFormEdit("options");
                var row = main_fun.get_row();
                $.yqWinPopEdit("save", {
                    row: row,
                    titles: page_fun.p_params.titles,
                    fk_rows: _opt.fk_rows === undefined ? [] : _opt.fk_rows,
                    _tb: _tb,
                    callback: function (tf, _row) {
                        if (tf) {
                            if (row["sid"] === undefined) {
                                main_fun.set_row(_row);
                            }
                        }
                    }
                });
            }
        }

        var wf_fun = {
            id: "main_wf",
            running: false, //执行中
            init: false,  //初始化
            bindingValue: null, //绑定值
            load: function () {
                if (wf_fun.running) {
                    return;
                }
                wf_fun.running = true;

                if (wf_fun.init) {
                    wf_fun.load_data();
                    return;
                }

                var opt = {
                    isFlow: false,    //是流程图显示
                    //width:500,
                    height: 200,
                    verId: main_fun.verId(),
                    dbName: "yqbase",
                    tbName: "ab_test_m",
                    row: {},
                    admin: true, //管理员
                    afterBindingTitle: function () {
                        wf_fun.init = true;
                        wf_fun.load_data();
                    },
                    afterSetRow: function () {
                        wf_fun.running = false;
                    },
                    beforeWfInit: function (wfinfo, init_data, callback) {    //如需要提示错误，添加 init_data["error"]="xxxx错误"
                        console.log("beforeWfInit", wfinfo, init_data);
                        callback(true, init_data);
                    },
                    afterWfInit: function (res) {
                        console.log("afterWfInit", res);
                    },
                    beforeWfSubmit: function (res, callback) {  //如需要提示错误，添加 res["error"]="xxxx错误"
                        console.log("beforeWfSubmit", res);
                        callback(true, res);
                    },
                    afterWfSubmit: function (res) {
                        console.log("afterWfSubmit", res);
                        if (res.error != 0) {
                            return;
                        }

                        if (page_fun.p_params.type == "wfmy") {
                            var p_row = $.yqWinPopEdit("get_prow");
                            p_row["state"] = res.wf.info.wfstate;
                            p_row["modifytime"] = res.wf.info.stamp;
                            $.yqWinPopEdit("refresh", {
                                row: p_row,
                                action: "upp",
                            });
                        } else if (page_fun.p_params.type == "wftodo") {
                            var p_row = $.yqWinPopEdit("get_prow");
                            $.yqWinPopEdit("refresh", {
                                row: p_row,
                                action: "del",
                            });
                        }

                        var wfstate = res.wf.info.wfstate;
                        var upp = true;
                        if (wfstate == 5) {
                            var row = main_fun.get_row();
                            if (row["wflock"]) {
                                upp = false;
                            }
                        }
                        if (upp) {
                            main_fun.upp_row();
                        }
                    },
                };

                $("#" + wf_fun.id).yqFlowList(opt);
            },
            load_data: function () {
                var row = main_fun.get_row();
                var sid = null;
                if (!(row === null)) {
                    sid = row.sid;
                }

                if (wf_fun.bindingValue === sid) {
                    wf_fun.running = false;
                    return;
                }
                wf_fun.bindingValue = sid;
                $("#" + wf_fun.id).yqFlowList("setRow", row);
            },
            get_wfs: function (callback) {
                $_yqFlow.wfRows(page_fun.p_params.options.verId,
                    function (res) {
                        console.log(res);
                        if (res.error == 0) {
                            callback(res.rows);
                        } else {
                            callback([]);
                        }
                    });
            }
        }
    </script>
    <script>
            (function ($) {
                $.fn.yqFlowList = function (opts, param) {
                    if (typeof opts == 'string') {
                        try {
                            return $.fn.yqFlowList.methods[opts](this, param);
                        } catch (e) {
                            console.log(e);
                            return null;
                        }
                    }

                    var $this = this;
                    var opt;
                    if ($this.data("yqtype") == "yqFlowList") {
                        destroy($this);
                    }

                    opt = $.extend({}, $.fn.yqFlowList.defaults, opts);
                    var $uniqueID = $this.attr("ID");
                    if ($uniqueID === undefined || $uniqueID === null || $uniqueID === "") {
                        $uniqueID = $.getUniqueID();
                        $this.attr("ID", $uniqueID);
                    }

                    if (opt.width === undefined) {
                        if ($this.width() > 0) {
                            opt.width = $this.width();
                        } else {
                            opt.width = 450;
                        }
                    }
                    else {
                        $this.width(opt.width);
                    }

                    if (opt.height === undefined) {
                        if ($this.height() > 0) {
                            opt.height = $this.height();
                        } else {
                            opt.height = 400;
                        }
                    }
                    else {
                        $this.height(opt.height);
                    }

                    //变量信息
                    $this.data("flowlist_opt", opt);
                    $this.data("yqtype", "yqFlowList");

                    init_ui($this);
                };

                $.fn.yqFlowList.defaults = {
                    ajaxUrl: "/_db.html",
                    isFlow: true,    //是流程图显示
                    dbName: "yqbase",
                    tbName: "ab_test_m",
                    row: {},
                    topicField: "textbox",
                    verId: null,
                    wfrows: [],  //可用流程
                    admin: false,  //管理员
                    afterBindingTitle: function () { },   //初始化完成后
                    afterSetRow: function () { },   //流程数据设置后
                    beforeWfInit: function (wfinfo, init_data, callback) {    //如需要提示错误，添加 init_data["error"]="xxxx错误"
                        callback(true, init_data);
                    },
                    afterWfInit: function (res) { },
                    beforeWfSubmit: function (res, callback) {  //如需要提示错误，添加 res["error"]="xxxx错误"
                        callback(true, res);
                    },
                    afterWfSubmit: function (res) { },
                };

                $.fn.yqFlowList.methods = {
                    options: function (jq) {
                        return options(jq);
                    },
                    resize: function (jq, res) {
                        var opt = options(jq);
                        resize(jq, res);
                    },
                    destroy: function (jq) {
                        var $object = jq;
                        destroy($object);
                    },
                    setRow: function (jq, row) {
                        setRow(jq, row);
                    },
                    showWf: function (jq, wfid) {
                        showWfById(jq, wfid);
                    },
                    showWf_2: function (jq, wfid) {
                        showWfById(jq, wfid, true);
                    },
                }

                function options($object) {
                    return $object.data("flowlist_opt");
                }

                function destroy($object) {
                    var opt = options($object);

                    $object.empty();
                }

                function init_ui($object) {
                    var opt = options($object);
                    var $uniqueID = $object.attr("ID");
                    opt.$toolbar = $('<div class="toolbar" style="padding:4px 5px;">工作流 </div>');

                    var columns = [[
                        { field: 'wfname', title: 'wfname', width: 150 },
                        {
                            field: 'topic', title: 'topic', width: 200,
                            formatter: function (value, row, index) {
                                if (value === undefined || value === null) {
                                    value = "[空]";
                                }

                                return '<a href="javascript:$(\'#' + $uniqueID + '\').yqFlowList(\'showWf\',\'' + row.sid + '\')">' + value + '</a>';
                            }
                        }, {
                            field: 'sp', title: '', width: 35, align: 'center',
                            formatter: function (value, row, index) {
                                var fa = "";
                                if (opt.isFlow) {
                                    fa = 'fa-file-code-o';
                                } else {
                                    fa = 'fa-share-alt';
                                }
                                return '<a class="fa ' + fa + '" href="javascript:$(\'#' + $uniqueID + '\').yqFlowList(\'showWf_2\',\'' + row.sid + '\')"></a>';
                            }
                        },
                        {
                            field: 'state', title: 'state', width: 100, align: 'center',
                            formatter: function (value, row, index) {
                                return $_yqFlow.formatWfState(value);
                            }
                        },
                        { field: 'c_username', title: 'c_username', width: 110, align: 'left' },
                        { field: 'createtime', title: 'createtime', width: 150, align: 'left' }
                    ]];

                    $object.datagrid({
                        width: opt.width - 15,
                        height: opt.height,
                        rownumbers: true,
                        singleSelect: true,
                        toolbar: opt.$toolbar,
                        columns: columns,
                        onLoadSuccess: function (data) {
                            console.log(data);
                            opt.afterSetRow.call($object);
                        },
                        onSelect: function (index, row) {
                            if (opt.admin) {
                                opt.$toolbar.find(".del").linkbutton({
                                    disabled: false
                                });
                            }
                        }
                    });

                    opt.$toolbar.empty();
                    opt.$toolbar.append("工作流");

                    var $a = $('<a id="btn" href="#">easyui</a>');
                    opt.$toolbar.append($a);
                    $a.linkbutton({
                        iconCls: 'icon-search'
                    });

                    $_yqFlow.wfRows(opt.verId,
                        function (res) {
                            console.log(res);
                            if (res.error == 0) {
                                opt.wfrows = res.rows;
                            } else {
                                opt.wfrows = [];
                            }

                            if (Object.getOwnPropertyNames(opt.row).length > 0) {
                                opt.afterBindingTitle.call($object);
                                setRow($object, opt.row);
                            } else {
                                opt.afterBindingTitle.call($object);
                            }
                        });
                }

                function setRow($object, row) {
                    var opt = options($object);
                    if (row === undefined || row === null) {
                        row = {};
                    }
                    opt.row = row;
                    if (row.sid === undefined) {
                        loadData($object, []);
                        return;
                    }

                    opt.$toolbar.empty();
                    opt.$toolbar.append("工作流 1");

                    getWfData($object, function (rows) {
                        loadData($object, rows);
                    });
                }

                function loadData($object, rows) {
                    var opt = options($object);

                    opt.$toolbar.empty();
                    opt.$toolbar.append("工作流&nbsp;&nbsp;");

                    var hasWf = false;
                    for (var i = 0; i < rows.length; i++) {
                        if (rows[i].state != 9) {
                            hasWf = true;
                            break;
                        }
                    }

                    if (!hasWf) {
                        var f_btn_run = false;
                        for (var i = 0; i < opt.wfrows.length; i++) {
                            var row = opt.wfrows[i];
                            var check_state = false;

                            var state = -1;
                            if (!(row.state_field === undefined ||
                                row.state_field === null
                            )) {
                                state = opt.row[row.state_field];
                                if (state === undefined) {
                                    state = -1;
                                }
                            }
                            var state_start = "";
                            if (!(row.state_start === undefined ||
                                row.state_start === null)) {
                                state_start = row.state_start;
                            }
                            var state_val = state_start.split(",");
                            console.log("ssss", state, state_val);
                            for (var j = 0; j < state_val.length; j++) {
                                if (state_val[j] === state.toString()) {
                                    check_state = true;
                                    break;
                                }
                            }

                            if (check_state) {
                                if (!f_btn_run) {
                                    f_btn_run = true;
                                } else {
                                    opt.$toolbar.append("&nbsp;");
                                }
                                var $a = $('<a href="#">' + row.name + '</a>');
                                opt.$toolbar.append($a);
                                $a.linkbutton({
                                    wfinfo: row, //工作流信息
                                    onClick: function () {
                                        var wfinfo = $(this).linkbutton("options").wfinfo;
                                        console.log(wfinfo);

                                        wfInit($object, wfinfo);
                                    }
                                });
                            }
                        }
                    }

                    if (opt.admin) {
                        opt.$toolbar.append("&nbsp;&nbsp;流程管理&nbsp;");
                        var $a = $('<a class="del" href="#">删除</a>');
                        opt.$toolbar.append($a);
                        $a.linkbutton({
                            disabled: true,
                            iconCls: 'yqwin-btn-icon fa fa-trash',
                            onClick: function () {
                                var row = $object.datagrid("getSelected");
                                if (row === null) {
                                    return;
                                }
                                $.yqConfirm("删除", "是否确定删除当前流程？", function () {
                                    wfDel($object, row.sid);
                                })
                            }
                        });
                    }

                    $object.datagrid("loadData", rows);
                }

                //取得工作流实例信息
                function getWfData($object, callback) {
                    var opt = options($object);

                    $_yqFlow.wfData({
                        dbname: opt.dbName,
                        tbname: opt.tbName,
                        id: opt.row.sid
                    },
                        function (res) {
                            console.log(res);
                            var rows = [];
                            if (res.error == 0) {
                                rows = res.rows;
                            }

                            callback(rows);
                        });
                }

                function wfInit($object, wfInfo) {
                    var opt = options($object);

                    var init_data = {
                        verId: wfInfo["sid"],   //流程版本id
                        case_when: "",     //流程过滤条件
                        params: {},
                        Parameter: {},
                        wfName: wfInfo.name,
                        topic: opt.row[opt.topicField],
                        dbName: opt.dbName,
                        tbName: opt.tbName,
                        tbId: opt.row.sid
                    }

                    opt.beforeWfInit.call($object, wfInfo, init_data,
                        function (tf, _init_data) {
                            if (tf) {
                                $_yqFlow.wfInit(_init_data, function (res) {
                                    if (res.error == 0) {
                                        var rows = $object.datagrid("getRows");
                                        rows.push(res.row);

                                        loadData($object, rows);
                                        $object.datagrid("selectRow", rows.length - 1);

                                        showWf($object, res.sid, res.wf, res.users)
                                    } else {
                                        $.yqMessager("error", res.info);
                                    }

                                    opt.afterWfInit.call($object, res);
                                });
                            } else {
                                if (!(_init_data["error"] === undefined)) {
                                    $.yqMessager("error", _init_data["error"]);
                                }
                            }
                        });
                }

                function showWfById($object, wfid, isSecond) {
                    var opt = options($object);

                    if (isSecond === undefined) {
                        isSecond = false;
                    }

                    $_yqFlow.wfJson(wfid, function (res) {
                        console.log("wfJson", res);
                        if (res.error == 0) {
                            showWf($object, wfid, res.wf, res.users, isSecond)
                        } else {
                            $.yqMessager("error", res.info);
                        }
                    });
                }

                function showWf($object, initId, wfdata, users, isSecond) {
                    var opt = options($object);

                    if (isSecond === undefined) {
                        isSecond = false;
                    }
                    //datagrid-view
                    var target = $object.closest('div.datagrid-view');
                    var prevent_e = $.getPreventDefault(target);
                    prevent_e.clientY -= $(target).height();
                    prevent_e.clientX = 50;

                    var h_ = window.innerHeight;
                    var w_ = window.innerWidth;

                    var isFlow = opt.isFlow;
                    if (isSecond) {
                        isFlow = !isFlow;
                    }

                    if (isFlow) {
                        if (h_ > 800) {
                            h_ = 800;
                        } else if (h_ < 400) {
                            h_ = 400;
                        }

                        if (w_ > 800) {
                            w_ = 800;
                        } else if (w_ < 400) {
                            w_ = 400;
                        }
                    } else {
                        if (h_ > 600) {
                            h_ = 600;
                        } else if (h_ < 400) {
                            h_ = 400;
                        }

                        if (w_ > 550) {
                            w_ = 550;
                        } else if (w_ < 400) {
                            w_ = 400;
                        }
                    }

                    var _pops = {
                        prevent_e: prevent_e,
                        mdiinfo: $.yqGetWindParams(),
                        title: "流程测试",
                        width: w_,
                        height: h_,
                        closeBtn: false,
                        closeBtnText: $.fn.yqUiExtText.btnNo,
                        onOpen: function ($body) {
                            var $dialog = this;

                            var $div_wf = $('<div class="div_wf" style="width:100%;height:100%;"></div>');
                            $body.append($div_wf);
                            if (window.top != window.self) {
                                $div_wf = window.top.$("#" + $body.attr("id")).find(".div_wf");
                            }

                            var opt_ = {
                                isFlow: isFlow,
                                initId: initId,   //实例流程id
                                value: wfdata,
                                type: 2,  //0-本地测试,1-服务端测试,2-执行流程   
                                users: users,
                                admin: opt.admin,
                                beforeBindingTitle: function (callback) {
                                    callback();
                                }, //标题绑定前
                                afterBindingTitle: function () {

                                },   //标题绑定后
                                beforeSubmit: function (res, callback) {  //审批提交前
                                    opt.beforeWfSubmit.call($object, res, function (tf, _res) {
                                        if (!tf) {
                                            if (!(_res["error"] === undefined)) {
                                                $.yqMessager("error", _res["error"]);
                                            }
                                        }

                                        callback(tf, _res);
                                    });
                                },
                                afterSubmit: function (res) {     //审批提交后
                                    if (!opt.admin) {
                                        $.yqDialog_fun.call($dialog, "close");
                                    }

                                    var rows = $object.datagrid("getRows");
                                    for (var i = 0; i < rows.length; i++) {
                                        if (rows[i].sid == res.sid) {
                                            if (rows[i].state != res.wf.info.wfstate) {
                                                rows[i].state = res.wf.info.wfstate;
                                                loadData($object, rows);
                                            }
                                            break;
                                        }
                                    }

                                    opt.afterWfSubmit.call($object, res);
                                }
                            };

                            $div_wf.yqFlowView(opt_);
                        }
                    };
                    if (window.top == window.self) {
                        $.yqDialog(_pops);
                    }
                    else {
                        window.top.$.yqDialog(_pops);
                    }
                }

                function wfDel($object, wfid) {
                    $_yqFlow.wfDel(wfid, function (res) {
                        console.log("wfDel", res);
                        if (res.error == 0) {
                            var rows = $object.datagrid("getRows");
                            for (var i = 0; i < rows.length; i++) {
                                if (rows[i].sid == wfid) {
                                    rows.splice(i, 1);
                                    loadData($object, rows);
                                    break;
                                }
                            }
                        }
                    })
                }
            })(jQuery);
    </script>
</body>

</html>